import React, { useEffect, useRef, useState } from 'react'
import { comRequest } from '../../request'
import * as echarts from 'echarts';
import moment from 'moment'
import { Button, Table, DatePicker, Select, Space, message, Calendar, Spin } from 'antd';
import "./index.less";
import locale from 'antd/es/date-picker/locale/zh_CN';
import { getweekday, getDefultDate, disabledDate } from '../../utils'
import 'dayjs/locale/zh-cn';
import dayjs from 'dayjs'
import { NextAndPreDayBar } from '../../components/NextAndPreDayBar'
const dateFormat = 'YYYY-MM-DD';
const KEY_CONFIG = {
    /** 上证50 */
    SZ50_JIN: '510050',
    /** hs300_jin */
    HS300_JIN: '510300',
    /** zz500_jin */
    ZZ500_JIN: '159919',
    /** 中证1000 */
    ZZ1000_JIN: 'zz1000_jin',

    /** SZ50_JUAN */
    SZ50_JUAN: 'SZ50_JUAN',
    /** HS300_JUAN */
    HS300_JUAN: 'HS300_JUAN',
    /** zz500_jin */
    ZZ500_JUAN: 'ZZ500_JUAN',
    /** 中证1000 */
    ZZ1000_JUAN: 'ZZ1000_JUAN',
}
const currentYeay = moment().format("YY") //24
const currentMonth = moment().format("MM") //01
const defaultDate = moment(getDefultDate()).format(dateFormat)
let add1 = Number(currentMonth) + 1
let defnum_add = add1 < 10 ? `0${add1}` : add1
const defaultLatastMonth = 510050
const defaultfARMonth = `${currentYeay}${defnum_add}`



export const QQlhb = ({ colorConfig }) => {
    const sunListRef = useRef([])
    const dateRef = useRef(defaultDate)
    const [moreList, setMoreList] = useState([])
    const [lessList, setLessList] = useState([])
    const [showDesc, setShowDesc] = useState(true)
    const [isLoading, setIsLoading] = useState(true)
    console.log("lessList")
    const [sumList, setSumList] = useState([
        {
            name: '上证50',
            key: KEY_CONFIG.SZ50_JIN,
            dayMore_number: 0,
            dayMore_cu: -0,
            dayLess_number: 0,
            dayLess_cu: -0,
        },
        {
            name: '沪深300-510300',
            key: KEY_CONFIG.HS300_JIN,
            dayMore_number: 0,
            dayMore_cu: -0,
            dayLess_number: 0,
            dayLess_cu: -0,
        },
        {
            name: '中证500-159919',
            key: KEY_CONFIG.ZZ500_JIN,
            dayMore_number: 0,
            dayMore_cu: -0,
            dayLess_number: 0,
            dayLess_cu: -0,
        },

    ])
    const [latastMonth, setLatastMonth] = useState(defaultLatastMonth)
    const [farMonth, setFarMonth] = useState(defaultfARMonth)
    const [monthSelectList, setMonthSelectList] = useState([])
    const [selectQueryDate, setSelectQueryDate] = useState(defaultDate)
    // 设置合约列表
    const initMonthDatas = () => {
        const temlist = [{
            label: '上证50',
            value: KEY_CONFIG.SZ50_JIN
        }, {
            label: '沪深300-510300',
            value: KEY_CONFIG.HS300_JIN
        },
        {
            label: '沪深300-159919',
            value: KEY_CONFIG.ZZ500_JIN
        },
        ]

        setMonthSelectList(temlist)

    }

    const queryDatas = async () => {

        if (["星期日", "星期六"].includes(getweekday(dateRef.current))) {
            message.warning("请选择周一到周五日期进行查询")
        }

        console.log("selectQueryDate", dateRef.current)
        const date_Q = dateRef.current
        setIsLoading(true)
        // 上证50
        await handleFetchData({
            requestKey: KEY_CONFIG.SZ50_JIN,
            SECURITY_CODE: KEY_CONFIG.SZ50_JIN,
            TRADE_DATE: date_Q,
            sortColumns: 'SPRANK',
            preTypeKey: 'SECURITY_CODE'
        })
        // 沪深300
        await handleFetchData({
            requestKey: KEY_CONFIG.HS300_JIN,
            SECURITY_CODE: KEY_CONFIG.HS300_JIN,
            TRADE_DATE: date_Q,
            sortColumns: 'SPRANK',
            preTypeKey: 'SECURITY_CODE'
        })
        // 沪深300
        await handleFetchData({
            requestKey: KEY_CONFIG.ZZ500_JIN,
            SECURITY_CODE: KEY_CONFIG.ZZ500_JIN,
            TRADE_DATE: date_Q,
            sortColumns: 'SPRANK',
            preTypeKey: 'SECURITY_CODE'
        })
        setIsLoading(false)
    }
    useEffect(() => {
        sunListRef.current = sumList
        initMonthDatas()

        queryDatas()
        handleFetchDataTable({
            requestKey: KEY_CONFIG.ZZ1000_JUAN,
            SECURITY_CODE: latastMonth,
            TRADE_DATE: dateRef.current,
            sortColumns: 'SPRANK',
            preTypeKey: 'SECURITY_CODE'
        })

    }, [])


    const handleFetchData = async ({ requestKey, SECURITY_CODE, TRADE_DATE, sortColumns, preTypeKey }) => {
        const url = 'https://datacenter-web.eastmoney.com/api/data/v1/get?reportName=RPT_FUTU_DAILYPOSITION&columns=ALL&filter=(SECURITY_CODE%3D%22IH2403%22)(TRADE_DATE%3D%272024-01-26%27)(TYPE%3D%222%22)(SPRANK%3C%3E9999)&sortTypes=1&sortColumns=SPRANK&source=WEB&client=WEB&_=1706369107342'


        const filterParams = {
            SECURITY_CODE,
            TRADE_DATE,
            TYPE: 2,
            LPRANK: 9999,
            preTypeKey: preTypeKey
        }
        console.log("参数", filterParams)

        const filterUrl = `(SECURITY_CODE%3D%22${filterParams.SECURITY_CODE}%22)(TRADE_DATE%3D%27${filterParams.TRADE_DATE}%27)`
        const getParams = {
            reportName: 'RPT_IF_BILLBOARD_TD',
            columns: 'ALL',
            filter: filterUrl,
            sortTypes: 1,
            pageNumber: 1,
            pageSize: 200,
            source: 'IFBILLBOARD',
            client: 'WEB'
        }

        const baseUrl = "https://datacenter-web.eastmoney.com/"
        const url1 = `${baseUrl}/api/data/v1/get?reportName=${getParams.reportName}&columns=${getParams.columns}&pageNumber=${getParams.pageNumber}&pageSize=${getParams.pageSize}&filter=${getParams.filter}&sortTypes=${getParams.sortTypes}&source=${getParams.source}&client=${getParams.client}`
        try {
            await comRequest({
                url: url,
            })
            const result = await comRequest({
                url: url1,
            })

            console.log("result", result.data)
            const zz500s = {
                key: requestKey,
                dayMore_number: 1000,
                dayMore_cu: 1999,
            }
            const list = result.data.data || []
            const sum_zz = list.reduce((pre, current) => {
                return {
                    dayMore_number: pre.dayMore_number + current.LONG_POSITION,
                    dayMore_cu: pre.dayMore_cu + current.LP_CHANGE,
                }
            }, {
                dayMore_number: 0,
                dayMore_cu: 0,
            })
            // setMoreList(result.data.data)

            const showData_more = list.filter(v => v.MEMBER_NAME_ABBR === '总成交量' && v.
                TRADE_TYPE
                ===
                "认购持仓量")?.[0]
            const showData_less = list.filter(v => v.MEMBER_NAME_ABBR === '总成交量' && v.
                TRADE_TYPE
                ===
                "认沽持仓量")?.[0]
            // const lessData = list?.[3]


            console.log("showData_more", showData_more)
            console.log("showData_less", showData_less)
            const temp = sunListRef.current.map(v => {
                let te = v
                if (v.key === requestKey) {
                    console.log("中证500调整")
                    te = {
                        ...te,
                        dayMore_number: showData_more.BUY_POSITION,
                        dayMore_cu: showData_more.BUY_POSITION_CHANGE,
                        dayLess_number: showData_less.SELL_POSITION,
                        dayLess_cu: showData_less.SELL_POSITION_CHANGE,
                    }
                }
                return te
            })
            sunListRef.current = temp
            console.log("temp", temp)
            setSumList(sunListRef.current)
        } catch (error) {
            console.log("error", error)

        }

    }
    console.log("moreList", moreList)

    const handleFetchDataTable = async ({ requestKey, SECURITY_CODE, TRADE_DATE, sortColumns, preTypeKey }) => {
        const url = 'https://datacenter-web.eastmoney.com/api/data/v1/get?reportName=RPT_FUTU_DAILYPOSITION&columns=ALL&filter=(SECURITY_CODE%3D%22IH2403%22)(TRADE_DATE%3D%272024-01-26%27)(TYPE%3D%222%22)(SPRANK%3C%3E9999)&sortTypes=1&sortColumns=SPRANK&source=WEB&client=WEB&_=1706369107342'


        const filterParams = {
            SECURITY_CODE,
            TRADE_DATE,
            TYPE: 2,
            LPRANK: 9999,
            preTypeKey: preTypeKey
        }
        console.log("参数", filterParams)

        const filterUrl = `(SECURITY_CODE%3D%22${filterParams.SECURITY_CODE}%22)(TRADE_DATE%3D%27${filterParams.TRADE_DATE}%27)`
        const getParams = {
            reportName: 'RPT_IF_BILLBOARD_TD',
            columns: 'ALL',
            filter: filterUrl,
            sortTypes: 1,
            pageNumber: 1,
            pageSize: 200,
            source: 'IFBILLBOARD',
            client: 'WEB'
        }

        const baseUrl = "https://datacenter-web.eastmoney.com/"
        const url1 = `${baseUrl}/api/data/v1/get?reportName=${getParams.reportName}&columns=${getParams.columns}&pageNumber=${getParams.pageNumber}&pageSize=${getParams.pageSize}&filter=${getParams.filter}&sortTypes=${getParams.sortTypes}&source=${getParams.source}&client=${getParams.client}`
        try {

            const result = await comRequest({
                url: url1,
            })

            console.log("result", result.data)

            const list = result.data.data || []
            setMoreList(list.filter(V => V?.TRADE_TYPE === '认购交易量'))
            setLessList(list.filter(V => V?.TRADE_TYPE === '认沽交易量'))

        } catch (error) {
            console.log("error", error)

        }

    }
    const columns = [
        {
            title: '认沽机构',
            dataIndex: 'MEMBER_NAME_ABBR',
            key: 'name',
        },
        {
            title: '持仓量',
            dataIndex: 'SELL_VOLUME',
            key: 'SELL_VOLUME',
        },
        {
            title: '增减',
            dataIndex: 'SELL_VOLUME_CHANGE',
            key: 'SELL_VOLUME_CHANGE',
        },


    ];
    const more_columns = [
        {
            title: '认购机构',
            dataIndex: 'MEMBER_NAME_ABBR',
            key: 'name',
        },
        {
            title: '持仓量',
            dataIndex: 'BUY_VOLUME',
            key: 'BUY_VOLUME',
        },
        {
            title: '增减',
            dataIndex: 'BUY_VOLUME_CHANGE',
            key: 'BUY_VOLUME_CHANGE',
        },


    ];

    const sumColumns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '多单量',
            dataIndex: 'dayMore_number',
            key: 'dayMore_number',
        },
        {
            title: '多单增减',
            dataIndex: 'dayMore_cu',
            key: 'dayMore_cu',
        },
        {
            title: '空单量',
            dataIndex: 'dayLess_number',
            key: 'dayLess_number',
        },
        {
            title: '空单增减',
            dataIndex: 'dayLess_cu',
            key: 'dayLess_cu',
        },
    ];

    const sum_option = {
        color: [colorConfig.red, colorConfig.green, colorConfig.red, colorConfig.green],
        legend: {
            data: ['多单', "空单", '多单增减', "空单增减",]
        },

        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ["上证50", '沪深300-510300', '沪深300-159919']
        },
        axisPointer: {
            type: 'shadow'
        },
        yAxis: {
            type: 'value'
        },
        label: {
            show: true,
            position: 'top'
        },
        series: [
            {
                name: '多单',
                data: sumList.map(v => ({
                    value: v.dayMore_number,
                    itemStyle: {
                        color: colorConfig.red
                    }
                })),
                type: 'bar'
            },
            {
                name: '空单',
                data: sumList.map(v => ({
                    value: v.dayLess_number,
                    itemStyle: {
                        color: colorConfig.green
                    }
                })),
                type: 'bar'
            },
            {
                name: '多单增减',
                data: sumList.map(v => ({
                    value: v.dayMore_cu,
                    itemStyle: {
                        color: colorConfig.red
                    }
                })),
                type: 'bar'
            },
            {
                name: '空单增减',
                data: sumList.map(v => ({
                    value: v.dayLess_cu,
                    itemStyle: {
                        color: colorConfig.green
                    }
                })),
                type: 'bar'
            },
        ]
    };
    useEffect(() => {
        redenEchart()
    }, [sumList])
    const redenEchart = () => {
        var myChart = echarts.init(document.getElementById('sum_echart_qq'));
        myChart.setOption(sum_option);
    }

    console.log("sumList", sumList)

    const onChangeDate = (date, dateString) => {
        console.log(date, dateString);
        if (moment(dateString).isAfter(moment().format('YYYY-MM-DD'))) {
            message.warning("请不要选择未到期日期")
            return
        }
        dateRef.current = dateString
        setSelectQueryDate(dateString)
        setSelectQueryDate(dateString)
    };
    const onPanelChange = (value, mode) => {
        console.log(111, value.format('YYYY-MM-DD'), mode);
        const dateString = value.format('YYYY-MM-DD')
        if (moment(dateString).isAfter(moment().format('YYYY-MM-DD'))) {
            return
        }
        dateRef.current = value.format('YYYY-MM-DD')
        setSelectQueryDate(value.format('YYYY-MM-DD'))
    };
    const onSelect = (newValue) => {
        console.log("99", newValue.format('YYYY-MM-DD'))
        const dateString = newValue.format('YYYY-MM-DD')
        if (moment(dateString).isAfter(moment().format('YYYY-MM-DD'))) {
            message.warning("请不要选择未到期日期")
            return
        }
        setSelectQueryDate(newValue.format('YYYY-MM-DD'))
        dateRef.current = newValue.format('YYYY-MM-DD')
        queryDatas()
    };

    return <div className='header-box'>
        <Spin tip="Loading" size="small" spinning={isLoading}>
            {/* 日期选择 */}
            <Space>
                <DatePicker onChange={onChangeDate}
                    // value={moment(selectQueryDate)}
                    defaultValue={dayjs(defaultDate)}
                    locale={locale}
                    disabledDate={disabledDate}
                    value={dayjs(selectQueryDate)}
                />


                {/* 设置合约 */}
                <h1>合约：{latastMonth}</h1>
                <Select
                    style={{
                        width: 120,
                    }}
                    options={monthSelectList}
                    onChange={(value) => {
                        setLatastMonth(value)
                    }}
                    defaultValue={defaultLatastMonth}
                />
                <Button onClick={() => {
                    queryDatas()
                    handleFetchDataTable({
                        requestKey: KEY_CONFIG.ZZ1000_JUAN,
                        SECURITY_CODE: latastMonth,
                        TRADE_DATE: selectQueryDate,
                        sortColumns: 'VOLUMERANK',
                        preTypeKey: 'VOLUMERANK'
                    })
                }} type='primary'>查询</Button>
                <Button onClick={() => {
                    setShowDesc(!showDesc)
                }} >{!showDesc ? "展开表格" : '隐藏表格'}</Button>
            </Space>
            {showDesc && <>
                <Table dataSource={moreList} columns={more_columns} />;
                <Table dataSource={lessList} columns={columns} />;
            </>}
            <div className='CalendarClass'>
                <Calendar onPanelChange={onPanelChange} onSelect={onSelect} fullscreen={false} defaultValue={dayjs(defaultDate)} disabledDate={disabledDate} value={dayjs(selectQueryDate)} />
            </div>
            <NextAndPreDayBar
                currentDay={selectQueryDate}
                onChange={(val) => {
                    setSelectQueryDate(val)
                    dateRef.current = val
                    queryDatas()
                }}  ></NextAndPreDayBar>
            <Table dataSource={sumList} columns={sumColumns} />;

            <div id="sum_echart_qq" className='sum_echart_class'></div>
        </Spin>
    </div >
}